package com.xhtt.smart.card.client.code;

import com.xhtt.smart.card.common.enums.FunctionTypeEnum;
import com.xhtt.smart.card.common.enums.TransferTypeEnum;
import com.xhtt.smart.card.common.msg.bean.MsgClientBean;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * @author wangze
 * @date 2018-07-04 15:09.
 **/
public class MessageClientDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {
        int length = in.readableBytes();
        System.out.println("数据可读长度为：" + length);
        //读取帧头
        byte frameHeaer = in.readByte();
        //读取传输码
        byte transferCode = in.readByte();
        //读取功能数
        in.readByte();
        //读取功能码
        byte functionCode = in.readByte();
        //TODO 判断是否是心跳数据
        //读取数据长度
        short dataLength = in.readUnsignedByte();


        byte[] data = null;
        if (dataLength > 0) {
            //读取 数据
            data = new byte[dataLength];
            in.readBytes(data);
        }
        //读取校验码
        in.readByte();
        //帧尾
        in.readByte();
        MsgClientBean message = new MsgClientBean();
        message.setData(data);
        message.setDataLength(dataLength);
        message.setFunctionType(FunctionTypeEnum.getEnumByCody(functionCode));
        message.setTransferType(TransferTypeEnum.getByIndex(transferCode));
        list.add(message);
    }
}
